#!/usr/bin/env bash

help(){
    cat<<__EOF__
Usage: m gatekeeper [OPTION] [ARGUMENTS]

Description: Manage Gatekeeper rules on macOS.

OPTIONS:
  --help                                    Show this help message and exit.
  --status                                  Show the current status of Gatekeeper.
  --list                                    List all Gatekeeper rules.
  --enable                                  Enable Gatekeeper
  --disable                                 Disable gatekeeper
  --enable-rule  RULE_NAME                  Enable a specific Gatekeeper rule.
  --disable-rule RULE_NAME                  Disable a specific Gatekeeper rule.
  --create-rule  RULENAME /path/to/program  Create a new Gatekeeper rule for the specified application.
__EOF__
}


gk_list(){
   if [ -z "$1" ]; then
       spctl --list
   else
       spctl --list --label "$1"
   fi
}

gk_toggle_rule(){
    local action="${1}"
    local rule_name="${2}"
    case "${action}" in
        enable) ;;
        disable) ;;
        *)
            echo "Invalid action: ${action}. Use 'enable' or 'disable'." >&2
            return 1
            ;;
    esac
    if [ -z "${rule_name}" ]; then
        echo "Rule name is required." >&2
        return 1
    fi
    spctl --${action} --label "${rule_name}"
}

gk_create_rule(){
    local rule_name="${1}"
    local app_path="${2}"
    if [ -z "${rule_name}" ] || [ -z "${app_path}" ]; then
        echo "Usage: m gatekeeper create-rule RULENAME /path/to/program" >&2
        return 1
    fi
    spctl --add --label "${rule_name}" "${app_path}"
}

option="${1}"
shift

case "${option}" in
    --help)
        help
        ;;
    --status)
        spctl --status
        ;;
    --list)
        gk_list "$*"
        ;;
    --enable)
        spctl --master-enable
        ;;
    --disable)
        spctl --master-disable
        ;;
    --enable-rule)
        gk_toggle_rule enable "$*"
        ;;
    --disable-rule)
        gk_toggle_rule disable "$*"
        ;;
    --create-rule)
        gk_create_rule "$@"
        ;;
    *)
        help
        ;;
esac
